package bancosys.tec.utils.db.executor;

import java.sql.Connection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jmine.tec.utils.UtilsMessages;
import bancosys.tec.utils.db.cleaner.DB2DbCleaner;

/**
 * Executa statements para o DB2.
 */
public class DB2DbExecutor extends JdbcDbExecutor {

    private Pattern datePattern = Pattern.compile("(\\{d)*\\s*\\'\\s*(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)\\s*\\'\\s*(\\})*");

    /**
     * @return o delimitador.
     */
    @Override
    public char getDelimiterChar() {
        return ';';
    }

    /**
     * Converte o statement para db2.
     * 
     * @param statement o statement.
     * @return o statement convertido.
     */
    @Override
    public String convertStatement(String statement) {
        String stm = statement;

        if (stm.contains("CURRENT_DATE")) {
            stm = stm.replaceAll("CURRENT_DATE", "CURRENT TIMESTAMP");
        }

        Matcher dateMatcher = this.datePattern.matcher(stm);
        while (dateMatcher.find()) {
            stm = dateMatcher.replaceAll("date('$2-$3-$4')");
            System.out.println("REPLACED DATE " + stm);
        }

        return stm;
    }

    /**
     * Executa o drop antes de executar os statements.
     * 
     * @param conn a conexão com banco de dados.
     * @throws CouldNotExecuteException falha na execução.
     */
    @Override
    protected void executeDrop(Connection conn) throws CouldNotExecuteException {
        LOG.info("Executando drop das tabelas");

        try {
            DB2DbCleaner cleaner =
                    new DB2DbCleaner(conn, this.getParameter("hibernate.default_schema", conn.getMetaData().getUserName().toUpperCase()));
            cleaner.drop();
        } catch (Exception e) {
            LOG.error(e.getCause());
            throw new CouldNotExecuteException(UtilsMessages.ERROR_CLEANING_DB.create(), e);
        }

        LOG.info("Finalizando drop das tabelas");
    }

}